package ULHT.LIG2N1.RC.SERVER;

import ULHT.LIG2N1.RC.VO.FileManage;
import java.io.IOException;
import java.net.*;

public class ServidorBackEnd {

    private static int TCPport = 6500, maxConnections = 0, UDPport = 9031, UDPmulticastPort = 9013;
    private static String hostAddress = "localhost";
    private static String MulticastGroupIP = "230.0.0.1";
    private static InetAddress group;
    private static String sessionFileName = "session.dat";

    public static void main(String[] args) {
        //GameVariables gameVariables = new GameVariables();
        int i = 0;
        System.out.println("Servidor a iniciar...\n\nA aguardar ligação dos clientes");

        try {
            ServerSocket TCPsocket = new ServerSocket(TCPport);
            DatagramSocket unicastSocket = new DatagramSocket();
            System.out.println(unicastSocket.getLocalPort());
  
            MulticastSocket multicastSocket = new MulticastSocket(UDPmulticastPort);
            group = InetAddress.getByName(MulticastGroupIP);
            Socket TCPClient;

            GameVariables gameVariables = new GameVariables();

            GameThread threadJogo = new GameThread(multicastSocket, group, UDPmulticastPort, gameVariables);
            Thread jogo = new Thread(threadJogo);
            jogo.start();

            System.out.println("LOCAL IP  : " + TCPsocket.getInetAddress().toString());
            
            while ((i++ < maxConnections) || (maxConnections == 0)) {
                TCPClient = TCPsocket.accept();
                ClientThread ThreadCliente = new ClientThread(TCPClient, /*unicastSocket,*/ gameVariables);
                Thread t = new Thread(ThreadCliente);
                t.start();
            }
        } catch (IOException ioe) {
            System.out.println("Erro de ligação ao socket TCP: " + ioe);
            ioe.printStackTrace();
        }
        FileManage.Delete(sessionFileName);
    }
}
